package com.haoshuang.zhouzhoubang.widget.camera;

import android.Manifest;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter4.BaseQuickAdapter;
import com.haoshuang.zhouzhoubang.R;
import com.haoshuang.zhouzhoubang.ui.dialog.ConfirmDialog;
import com.luck.lib.camerax.CustomCameraConfig;
import com.luck.lib.camerax.listener.CameraListener;
import com.luck.lib.camerax.listener.ClickListener;
import com.luck.lib.camerax.listener.IObtainCameraView;
import com.luck.lib.camerax.listener.ImageCallbackListener;
import com.luck.lib.camerax.permissions.PermissionChecker;
import com.luck.lib.camerax.permissions.PermissionResultCallback;
import com.luck.lib.camerax.utils.SimpleXSpUtils;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.lxj.xpopup.XPopup;
import com.mufeng.libs.utils.view.RecyclerViewKtxKt;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function1;

/**
 * @author：luck
 * @date：2021/11/29 7:50 下午
 * @describe：PictureCameraActivity
 */
public class MyPictureCameraActivity extends AppCompatActivity implements IObtainCameraView {
    /**
     * PermissionResultCallback
     */
    private PermissionResultCallback mPermissionResultCallback;

    private CustomCameraView mCameraView;
    private RecyclerView recyclerView;
    private LinearLayout llCameraResult;
    private TextView tvConfirm;

    private ArrayList<LocalMedia> data = new ArrayList<>();
    private MyPictureCameraAdapter adapter = new MyPictureCameraAdapter(data);

    private int imageMaxCount = 1;
    private int videoMaxCount = 1;

    private SimpleCameraConfig simpleCameraConfig;

    // 提交按钮重复点击
    private Long confirmTime = 0L;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        imageMaxCount = getIntent().getIntExtra(MySimpleCamera.EXTRA_IMAGE_MAX_COUNT, 1);
        videoMaxCount = getIntent().getIntExtra(MySimpleCamera.EXTRA_VIDEO_MAX_COUNT, 1);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
            getWindow().setAttributes(lp);
        }
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_continuous_capture);

        simpleCameraConfig = SimpleCameraProviders.getInstance().getSelectorConfig();

        mCameraView = findViewById(R.id.customCameraView);
        recyclerView = findViewById(R.id.recyclerView);
        llCameraResult = findViewById(R.id.llCameraResult);
        tvConfirm = findViewById(R.id.tvConfirm);

        RecyclerViewKtxKt.horizontal(recyclerView,1,false);
        recyclerView.setAdapter(adapter);
        adapter.addOnItemChildClickListener(R.id.ivClose, new BaseQuickAdapter.OnItemChildClickListener<LocalMedia>() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<LocalMedia, ?> baseQuickAdapter, @NonNull View view, int i) {
                // 点击关闭按钮
                data.remove(i);
                adapter.notifyItemRemoved(i);
            }
        });

        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Long time = System.currentTimeMillis();
                if (time - confirmTime > 500){
                    handleCameraSuccess();
                }
                confirmTime = System.currentTimeMillis();
            }
        });

        mCameraView.post(new Runnable() {
            @Override
            public void run() {
                mCameraView.setCameraConfig(getIntent());
            }
        });
        mCameraView.setImageCallbackListener(new ImageCallbackListener() {
            @Override
            public void onLoadImage(String url, ImageView imageView) {
                if (CustomCameraConfig.imageEngine != null) {
                    CustomCameraConfig.imageEngine.loadImage(imageView.getContext(), url, imageView);
                }
            }
        });
        mCameraView.setCameraListener(new CameraListener() {
            @Override
            public void onPictureSuccess(@NonNull String url) {
                List<LocalMedia> imageList = data.stream().filter(new Predicate<LocalMedia>() {
                    @Override
                    public boolean test(LocalMedia localMedia) {
                        return PictureMimeType.isHasImage(localMedia.getMimeType());
                    }
                }).collect(Collectors.toList());
                if (imageMaxCount > imageList.size()) {
                    addMedia(url);
                }else{
                    mCameraView.onCancelMedia();
                    ToastUtils.showShort("最多可拍摄"+imageMaxCount+"张照片");
                }
            }

            @Override
            public void onRecordSuccess(@NonNull String url) {
                List<LocalMedia> videoList = data.stream().filter(new Predicate<LocalMedia>() {
                    @Override
                    public boolean test(LocalMedia localMedia) {
                        return PictureMimeType.isHasVideo(localMedia.getMimeType());
                    }
                }).collect(Collectors.toList());
                if (videoMaxCount > videoList.size()) {
                    addMedia(url);
                }else{
                    mCameraView.onCancelMedia();
                    ToastUtils.showShort("最多可录制"+videoMaxCount+"个视频");
                }
            }

            @Override
            public void onError(int videoCaptureError, @NonNull String message,
                                @Nullable Throwable cause) {
                Toast.makeText(MyPictureCameraActivity.this.getApplicationContext(),
                        message, Toast.LENGTH_LONG).show();
            }
        });

        mCameraView.setOnCancelClickListener(new ClickListener() {
            @Override
            public void onClick() {
                handleCameraCancel();
            }
        });
    }

    private void addMedia(String url){
        llCameraResult.setVisibility(View.VISIBLE);
        LocalMedia localMedia = LocalMedia.generateLocalMedia(this, url);
        data.add(localMedia);
        adapter.notifyDataSetChanged();
        recyclerView.scrollToPosition(data.size() - 1);
        mCameraView.rePreview();
    }

    private void handleCameraSuccess() {
        // 获取所有的文件
        Intent intent = new Intent();
        intent.putExtra("picture_camera", data.toArray(new LocalMedia[]{}));
        setResult(RESULT_OK, intent);
        simpleCameraConfig.onResultCallListener.onResult(data);
        onBackPressed();
    }

    private void handleCameraCancel() {

        if (!data.isEmpty()){
            new XPopup.Builder(this)
                    .asCustom(new ConfirmDialog(
                            MyPictureCameraActivity.this,
                            "温馨提示",
                            "存在已拍摄文件, 是否确认返回",
                            "取消",
                            "确认返回",
                            Gravity.CENTER,
                            false, false,
                            aBoolean -> {

                                return null;
                            },
                            () -> {
                                simpleCameraConfig.onResultCallListener.onCancel();
                                setResult(RESULT_CANCELED);
                                onBackPressed();
                                return null;
                            }
                    ))
                    .show();

            return;
        }
        simpleCameraConfig.onResultCallListener.onCancel();
        setResult(RESULT_CANCELED);
        onBackPressed();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            mCameraView.onCancelMedia();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mCameraView.onConfigurationChanged(newConfig);
    }

    @Override
    public void onBackPressed() {
        CustomCameraConfig.destroy();
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.Q) {
            finishAfterTransition();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (CustomCameraConfig.explainListener != null) {
            CustomCameraConfig.explainListener.onDismiss(mCameraView);
        }
        if (requestCode == PermissionChecker.PERMISSION_SETTING_CODE) {
            if (PermissionChecker.checkSelfPermission(this,new String[]{Manifest.permission.CAMERA})) {
                mCameraView.buildUseCameraCases();
            } else {
                SimpleXSpUtils.putBoolean(this,Manifest.permission.CAMERA, true);
                handleCameraCancel();
            }
        } else if (requestCode == PermissionChecker.PERMISSION_RECORD_AUDIO_SETTING_CODE) {
            if (!PermissionChecker.checkSelfPermission(this, new String[]{Manifest.permission.RECORD_AUDIO})) {
                SimpleXSpUtils.putBoolean(this, Manifest.permission.RECORD_AUDIO, true);
                Toast.makeText(getApplicationContext(), "Missing recording permission", Toast.LENGTH_LONG).show();
            }
        }
    }

    /**
     * Set PermissionResultCallback
     *
     * @param callback
     */
    public void setPermissionsResultAction(PermissionResultCallback callback) {
        mPermissionResultCallback = callback;
    }

    @Override
    protected void onDestroy() {
        mCameraView.onDestroy();
        super.onDestroy();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (mPermissionResultCallback != null) {
            PermissionChecker.getInstance()
                    .onRequestPermissionsResult(grantResults, mPermissionResultCallback);
            mPermissionResultCallback = null;
        }
    }

    @Override
    public ViewGroup getCustomCameraView() {
        return mCameraView;
    }
}
